package com.slipper.ai.model.chat.support;

import com.slipper.ai.model.chat.ChatModelBuilder;
import com.slipper.constants.Constants;
import com.slipper.core.gson.GsonUtil;
import com.slipper.exception.CommonException;
import com.slipper.system.ai.bo.AiModelBO;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.zhipuai.ZhiPuAiChatModel;
import org.springframework.ai.zhipuai.ZhiPuAiChatOptions;
import org.springframework.ai.zhipuai.api.ZhiPuAiApi;

import java.util.Map;

public class ZhipuaiChatModelBuilder implements ChatModelBuilder {
    @Override
    public ChatModel build(AiModelBO model) {
        Map<String, Object> options = GsonUtil.toMap(model.getParamJson());
        if (options == null
                || options.isEmpty()
                || !options.containsKey("apiUrl")
                || !options.containsKey("apiKey")) {
            throw new CommonException("参数配置不正确！");
        }

        String apiUrl = (String) options.get("apiUrl");
        String apiKey = (String) options.get("apiKey");

        ZhiPuAiChatOptions.Builder builder = ZhiPuAiChatOptions.builder().model(model.getSupplierModelName());
        if (Constants.YES.equals(options.get("use_temperature")) && options.get("temperature") != null) {
            builder.temperature((double) options.get("temperature"));
        }
        if (Constants.YES.equals(options.get("use_top_p")) && options.get("top_p") != null) {
            builder.topP((double) options.get("top_p"));
        }
//        if (Constants.YES.equals(options.get("use_presence_penalty")) && options.get("presence_penalty") != null) {
//            builder.presencePenalty((double) options.get("presence_penalty"));
//        }
//        if (Constants.YES.equals(options.get("use_frequency_penalty")) && options.get("frequency_penalty") != null) {
//            builder.frequencyPenalty((double) options.get("frequency_penalty"));
//        }
        if (Constants.YES.equals(options.get("use_max_tokens")) && options.get("max_tokens") != null) {
            builder.maxTokens((int) options.get("max_tokens"));
        }

        return new ZhiPuAiChatModel(new ZhiPuAiApi(apiUrl, apiKey), builder.build());
    }
}
